#-*- coding: UTF-8 -*-
from pyramid.httpexceptions import HTTPFound
from pyramid.security import remember
from pyramid.security import forget




from scp.modelo.models import DBSession
from scp.modelo.Usuario import Usuario

from pyramid.response import Response
from pyramid.view import view_config
import json


#@view_config(renderer='json')
def login(request):
	"""Método Controlador de la Autenticación, contrala las peticiones /login y los submits del Form de Login
		@param request: Petición Http del cliente. 	
	"""	
	
	print '>>>>>>>>>>>>>>>inicio de metodo login<<<<<<<<<<<<<<<<<<<<<<'
	print '>>>>>>>>>>>>>>>request inicio<<<<<<<<<<<<<<<<<<<<<<'
	
	print request

	print '>>>>>>>>>>>>>>>request fin<<<<<<<<<<<<<<<<<<<<<<'


	print '>>>>>>>>>>>>>>>request.metodo<<<<<<<<<<<<<<<<<<<<<<'
	
	methodRequest = request.method
	
	print request.method
	print '>>>>>>>>>>>>>>>request.metodo<<<<<<<<<<<<<<<<<<<<<<'
	
	login_url = request.route_url('login')

	

	referrer = request.url
	

	if referrer == login_url:
		referrer = '/' # never use the login form itself as came_from
	came_from = request.params.get('came_from', referrer)
   

	message = ''
	login = ''
	password = ''

		

	if methodRequest == 'POST':
		login = request.params['loginUsername']
		password = request.params['loginPassword']
		
		print "fue un submit-->esto son los parametros recibidos"
		print request.params
		

		if login != None and login != "" and password != None and password != "": 

			session = DBSession()
			
			usuario = session.query(Usuario).filter_by(username=login).first()
			
			
			if usuario != None:
			
				if usuario.password == password:
					print "esto trajimos de la BD-->" + usuario.username
					
					headers = remember(request, login) 
					
					response = Response(headers=headers)
					response.body = json.dumps(dict(success = True,rsp='ok', msg = 'Autenticación Exitosa'))
					response.content_type = 'application/json'
					
					return response
				
				else:
					message = 'Contrasenha incorrecta'
					password = ""
					response = Response()
					response.body = json.dumps(dict(success = True,rsp='er', msg = message, password = password, user = login))
					response.content_type = 'application/json'
					
					return response
					
			else:
				message = 'Usuario ingresado no existe'
				login = ""
				password = ""
				response = Response()
				response.body = json.dumps(dict(success = True,rsp='er', msg = message, password = password, user = login))
				response.content_type = 'application/json'
				
				return response
				
				
		

	return {'content':'Hello!'}

	
    
def logout(request):
    """Método que controla la anulación de la sesión de Usuario, se ejecuta en el Servidor, url asociada: /logout.
		@param request: Petición Http del cliente. 	
	"""
    headers = forget(request)
    return HTTPFound(location = request.route_url('login'),
                     headers = headers)
